package com.laiqilin.handler;

import com.laiqilin.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1) // 设置异常处理器的优先级
@Configuration
@Slf4j
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    /**
     * 处理异常并返回自定义错误响应
     *
     * @param exchange 请求和响应的上下文
     * @param ex 捕获的异常
     * @return Mono<Void>
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        // 如果响应已经提交，则直接返回异常
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }

        // 异常消息处理
        String msg;
        if (ex instanceof NotFoundException) {
            msg = "服务未找到"; // 服务未找到异常
        } else if (ex instanceof ResponseStatusException) {
            msg = ((ResponseStatusException) ex).getMessage(); // 响应状态异常
        } else {
            msg = "内部服务器错误"; // 其他未知异常
        }

        // 日志记录异常信息
        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());

        // 返回自定义的错误响应
        return ResponseUtil.webFluxResponseWriter(response, msg);
    }
}
